package com.zhitong.money.services;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhitong.money.entity.Employee;
import com.zhitong.money.entity.User;
import com.zhitong.money.exception.AddException;
import com.zhitong.money.exception.DeleteException;
import com.zhitong.money.exception.RepeatException;
import com.zhitong.money.exception.UpdateException;
import com.zhitong.money.mapper.EmployeeMapper;
import com.zhitong.money.mapper.UserMapper;
import com.zhitong.money.mapper.UserRolemapper;
import com.zhitong.money.services.api.IUserService;
import com.zhitong.money.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class UserService implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private UserRolemapper userRolemapper;


    @Override
    public User findUserByUserName(String userName) throws Exception {
        User userByUserName = userMapper.findUserByUserName(userName.trim());
        if (userByUserName == null){
            throw new NullPointerException("findUserByUserName:查询为空");
        }
        return userByUserName;
    }

    @Override
    public User findUserById(String id) throws Exception {
        User userByid = userMapper.findUserByid(id);
        if (userByid == null){
            throw new NullPointerException("findUserById:查询为空");
        }
        return userByid;
    }

    @Override
    public User findUserByTid(String tid) throws Exception {
        return userMapper.findUserByTid(tid);
    }

    @Override
    public List<User> findUserByMap(Map<String, Object> map) throws Exception {

        List<User> userByMap = userMapper.findUserByMap(map);
        if (userByMap==null){
            throw new NullPointerException("findUserByMap:查询为空");
        }
        return userByMap;

    }

    @Override
    public List<User> findAllUser() throws Exception {

        try {
           List<User> users = userMapper.findAllUser();
            if (users == null){
                throw new NullPointerException();
            }
            return users;
        } catch (Exception e) {
            log.error("查询所有用户失败:"+e.getMessage());
            throw e;
        }

    }

    @Override
    public PageInfo findUserByPage(Map<String,Object> map) throws Exception {
        int pageNum=map.containsKey("pageNum")?(int)map.get("pageNum"):1;
        int pageSize=map.containsKey("pageSize")?(int)map.get("pageSize"):5;

        PageHelper.startPage(pageNum,pageSize);
        List<User> userByMap = userMapper.findUserByMap(map);
        if(userByMap==null){
            throw new NullPointerException("finUserByPage:查询为空");
        }
        return new PageInfo(userByMap);
    }

    @Transactional
    @Override
    public void addUser(Map<String,Object> map) throws Exception {
        //判断是否重复
        User userByUserName = userMapper.findUserByUserName(map.get("userName").toString().trim());
        User userByTid = userMapper.findUserByTid(map.get("tid").toString());
        if (userByUserName!=null || userByTid!=null){
            log.info("用户名重复或者该用户已有账号");
            throw new RepeatException("用户名重复或者该员工已有账号");
        }

        //判断该员工是否存在
        Employee tid = employeeMapper.findEmployeeByTellerId(map.get("tid").toString());
        if (tid==null){
            throw new NullPointerException("addUser--->该员工编号不存在");
        }


        try {
            //密码编码
            map.put("password",MD5Util.encryptPassword(map.get("userName").toString(), map.get("password").toString()));
            map.put("id", UUID.randomUUID().toString().replace("-",""));
            String iconUrl =map.get("iconUrl").toString();
            if (iconUrl==null || iconUrl.equals("")){
                map.put("iconUrl","http://127.0.0.1:8090/icon.jpg");
            }

            //添加角色关系
            List<String> roles = (List<String>) map.get("roles");
           if(roles!=null && !roles.isEmpty()){
               for (String rid:roles) {
                   userRolemapper.add(map.get("id").toString(),rid);
               }
           }


            userMapper.addUser(map);
            employeeMapper.updateUStatusByTid(map.get("tid").toString(),"01");
        } catch (Exception e) {
            log.error("添加用户失败:"+e.getMessage());
            throw new AddException();
        }

    }

    @Transactional
    @Override
    public void updateUser(Map<String,Object> map) throws Exception {
        try {
            String id =map.get("id").toString();
            //先删除原有的角色关系
            List<String> roles =(List<String>) map.get("roles");
            //添加现有的角色关系
            if (roles!=null){
                userRolemapper.deleteByUid(id);
                if (!roles.isEmpty()){
                    for (String rid:roles) {
                        userRolemapper.add(id,rid);
                    }
                }
            }
            //密码加密
            String userName=(String) map.get("userName");
            String pwd= (String) map.get("password");
            if(pwd!=null && !pwd.equals("")){
                map.put("password",MD5Util.encryptPassword(userName,pwd));
            }

            //更新用户
            map.put("updateTime",new Date());
            userMapper.updateUser(map);
        } catch (Exception e) {
            log.error("更新用户失败:"+e.getMessage());
            throw new UpdateException();
        }
    }

    @Override
    public void updateLastTime(Map<String, Object> map) throws Exception {
        userMapper.updateLastTime(map);
    }

    @Transactional
    @Override
    public void delUser(String id) throws Exception {
        try {
            //删除用户与角色的关系
            userRolemapper.deleteByUid(id);
            //设置员工的用户状态
            User userByid = userMapper.findUserByid(id);
            employeeMapper.updateUStatusByTid(userByid.getTid(),"00");


            userMapper.delUser(id);
        } catch (Exception e) {
            throw new DeleteException("delUer--->:"+e.getMessage());
        }
    }

    @Transactional
    @Override
    public void delUserByIds(Map<String,Object> map) throws Exception {
        try {
            List<String> ids=(List<String>) map.get("delList");
            List<String> tids=(List<String>) map.get("delTids");
            //删除用户与角色的关系
            userRolemapper.deleteByUids(ids);
            //设置员工的用户状态
            employeeMapper.updateUStatusByTids(tids,"02");

            userMapper.delUserByIds(ids);
        } catch (Exception e) {
            throw new DeleteException("delUerByIds:"+e.getMessage());
        }

    }

    @Override
    public void delUserByTid(String tid) throws Exception {

    }

    @Transactional
    @Override
    public void delUserByTids(List<String> tids) throws Exception {
        //删除用户与角色的关系
        List<String> idsByTids = userMapper.findIdsByTids(tids);
        if (idsByTids!=null && !idsByTids.isEmpty()) {
            userRolemapper.deleteByUids(idsByTids);
        }

        userMapper.delUserByTids(tids);
    }


}
